<template>
  <div class="modal-system">
    <TransitionGroup
      name="modal"
      tag="div"
    >
      <div
        v-for="modal in modals"
        :key="modal.id"
        :class="[
          'modal-backdrop',
          { 'modal-backdrop--blur': modal.blur !== false }
        ]"
        @click="handleBackdropClick(modal)"
      >
        <div
          :class="[
            'modal',
            `modal--${modal.size || 'medium'}`,
            { 'modal--fullscreen': modal.fullscreen }
          ]"
          @click.stop
        >
          <!-- 模态框头部 -->
          <div v-if="modal.showHeader !== false" class="modal__header">
            <div class="modal__title">
              <component
                v-if="modal.icon"
                :is="modal.icon"
                class="modal__icon"
              />
              {{ modal.title }}
            </div>
            
            <div class="modal__header-actions">
              <button
                v-for="action in modal.headerActions"
                :key="action.id"
                :class="['modal__header-action', `modal__header-action--${action.type}`]"
                :title="action.tooltip"
                @click="handleHeaderAction(modal, action)"
              >
                <component :is="action.icon" />
              </button>
              
              <button
                v-if="modal.closable !== false"
                class="modal__close"
                title="关闭"
                @click="closeModal(modal.id)"
              >
                <CloseIcon />
              </button>
            </div>
          </div>
          
          <!-- 模态框内容 -->
          <div class="modal__content">
            <component
              v-if="modal.component"
              :is="modal.component"
              v-bind="modal.props"
              @close="closeModal(modal.id)"
              @update="(data) => updateModal(modal.id, data)"
            />
            
            <div v-else-if="modal.content" v-html="modal.content" />
            
            <div v-else class="modal__message">
              {{ modal.message }}
            </div>
          </div>
          
          <!-- 模态框底部 -->
          <div v-if="modal.actions && modal.actions.length > 0" class="modal__footer">
            <button
              v-for="action in modal.actions"
              :key="action.id"
              :class="[
                'modal__action',
                `modal__action--${action.type || 'secondary'}`,
                { 'modal__action--loading': action.loading }
              ]"
              :disabled="action.disabled"
              @click="handleAction(modal, action)"
            >
              <component
                v-if="action.icon && !action.loading"
                :is="action.icon"
                class="modal__action-icon"
              />
              <LoadingIcon v-if="action.loading" class="modal__action-icon animate-spin" />
              {{ action.label }}
            </button>
          </div>
          
          <!-- 调整大小手柄 -->
          <div
            v-if="modal.resizable"
            class="modal__resize-handle"
            @mousedown="startResize(modal, $event)"
          />
        </div>
      </div>
    </TransitionGroup>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useModalStore } from '@/stores/modal'
import type { Modal, ModalAction, HeaderAction } from '@/types/modal'

// 图标组件
const CloseIcon = () => h('svg', { 
  viewBox: '0 0 24 24', 
  fill: 'currentColor',
  class: 'w-5 h-5'
}, [
  h('path', { d: 'M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z' })
])

const LoadingIcon = () => h('svg', { 
  viewBox: '0 0 24 24', 
  fill: 'currentColor',
  class: 'w-4 h-4'
}, [
  h('path', { d: 'M12,4a8,8,0,0,1,7.89,6.7A1.53,1.53,0,0,0,21.38,12h0a1.5,1.5,0,0,0,1.48-1.75,11,11,0,0,0-21.72,0A1.5,1.5,0,0,0,2.62,12h0a1.53,1.53,0,0,0,1.49-1.3A8,8,0,0,1,12,4Z' })
])

const modalStore = useModalStore()

const modals = computed(() => modalStore.modals)
const resizing = ref<{ modal: Modal; startX: number; startY: number; startWidth: number; startHeight: number } | null>(null)

const handleBackdropClick = (modal: Modal) => {
  if (modal.closeOnBackdrop !== false) {
    closeModal(modal.id)
  }
}

const handleHeaderAction = (modal: Modal, action: HeaderAction) => {
  if (action.handler) {
    action.handler(modal, action)
  }
}

const handleAction = (modal: Modal, action: ModalAction) => {
  if (action.handler) {
    const result = action.handler(modal, action)
    
    // 如果返回 Promise，显示加载状态
    if (result instanceof Promise) {
      action.loading = true
      result
        .then(() => {
          if (action.autoClose !== false) {
            closeModal(modal.id)
          }
        })
        .catch((error) => {
          console.error('Modal action error:', error)
          // 可以在这里显示错误通知
        })
        .finally(() => {
          action.loading = false
        })
    } else if (action.autoClose !== false) {
      closeModal(modal.id)
    }
  } else if (action.autoClose !== false) {
    closeModal(modal.id)
  }
}

const closeModal = (id: string) => {
  modalStore.closeModal(id)
}

const updateModal = (id: string, data: any) => {
  modalStore.updateModal(id, data)
}

// 调整大小功能
const startResize = (modal: Modal, event: MouseEvent) => {
  const modalElement = event.target?.closest('.modal') as HTMLElement
  if (!modalElement) return
  
  const rect = modalElement.getBoundingClientRect()
  resizing.value = {
    modal,
    startX: event.clientX,
    startY: event.clientY,
    startWidth: rect.width,
    startHeight: rect.height
  }
  
  document.addEventListener('mousemove', handleResize)
  document.addEventListener('mouseup', stopResize)
  document.body.style.cursor = 'nw-resize'
  event.preventDefault()
}

const handleResize = (event: MouseEvent) => {
  if (!resizing.value) return
  
  const { modal, startX, startY, startWidth, startHeight } = resizing.value
  const deltaX = event.clientX - startX
  const deltaY = event.clientY - startY
  
  const newWidth = Math.max(300, startWidth + deltaX)
  const newHeight = Math.max(200, startHeight + deltaY)
  
  // 更新模态框大小
  updateModal(modal.id, {
    style: {
      width: `${newWidth}px`,
      height: `${newHeight}px`
    }
  })
}

const stopResize = () => {
  resizing.value = null
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
  document.body.style.cursor = ''
}

// 键盘快捷键
const handleKeydown = (event: KeyboardEvent) => {
  const topModal = modals.value[modals.value.length - 1]
  if (!topModal) return
  
  if (event.key === 'Escape' && topModal.closable !== false) {
    closeModal(topModal.id)
    event.preventDefault()
  }
  
  if (event.key === 'Enter' && topModal.actions) {
    const primaryAction = topModal.actions.find(a => a.type === 'primary')
    if (primaryAction && !primaryAction.disabled) {
      handleAction(topModal, primaryAction)
      event.preventDefault()
    }
  }
}

// 阻止背景滚动
const preventScroll = (event: Event) => {
  if (modals.value.length > 0) {
    event.preventDefault()
  }
}

onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
  document.addEventListener('wheel', preventScroll, { passive: false })
  document.addEventListener('touchmove', preventScroll, { passive: false })
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
  document.removeEventListener('wheel', preventScroll)
  document.removeEventListener('touchmove', preventScroll)
  
  if (resizing.value) {
    stopResize()
  }
})
</script>

<style scoped>
.modal-system {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: var(--z-modal);
  pointer-events: none;
}

.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: var(--bg-overlay);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-lg);
  pointer-events: auto;
}

.modal-backdrop--blur {
  backdrop-filter: blur(4px);
}

.modal {
  background: var(--bg-modal);
  border: 1px solid var(--border-secondary);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-xl);
  display: flex;
  flex-direction: column;
  max-width: 90vw;
  max-height: 90vh;
  position: relative;
  overflow: hidden;
}

.modal--small {
  width: 400px;
  min-height: 200px;
}

.modal--medium {
  width: 600px;
  min-height: 300px;
}

.modal--large {
  width: 800px;
  min-height: 400px;
}

.modal--extra-large {
  width: 1000px;
  min-height: 500px;
}

.modal--fullscreen {
  width: 100vw;
  height: 100vh;
  max-width: none;
  max-height: none;
  border-radius: 0;
}

.modal__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-lg);
  border-bottom: 1px solid var(--border-primary);
  background: rgba(255, 255, 255, 0.02);
}

.modal__title {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  font-size: var(--text-lg);
  font-weight: 600;
  color: var(--text-primary);
}

.modal__icon {
  width: 20px;
  height: 20px;
  color: var(--primary-color);
}

.modal__header-actions {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.modal__header-action {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--radius-md);
  color: var(--text-muted);
  transition: all var(--transition-fast);
  cursor: pointer;
}

.modal__header-action:hover {
  color: var(--text-primary);
  background: rgba(255, 255, 255, 0.1);
}

.modal__header-action--primary {
  color: var(--primary-color);
}

.modal__header-action--danger {
  color: var(--error-color);
}

.modal__close {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--radius-md);
  color: var(--text-muted);
  transition: all var(--transition-fast);
  cursor: pointer;
}

.modal__close:hover {
  color: var(--text-primary);
  background: rgba(255, 255, 255, 0.1);
}

.modal__content {
  flex: 1;
  padding: var(--spacing-lg);
  overflow-y: auto;
}

.modal__message {
  color: var(--text-secondary);
  line-height: 1.6;
}

.modal__footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: var(--spacing-sm);
  padding: var(--spacing-lg);
  border-top: 1px solid var(--border-primary);
  background: rgba(255, 255, 255, 0.02);
}

.modal__action {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  padding: var(--spacing-sm) var(--spacing-lg);
  border-radius: var(--radius-md);
  font-size: var(--text-sm);
  font-weight: 500;
  transition: all var(--transition-normal);
  cursor: pointer;
  min-width: 80px;
  justify-content: center;
}

.modal__action:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.modal__action--primary {
  background: var(--primary-color);
  color: var(--bg-primary);
}

.modal__action--primary:hover:not(:disabled) {
  background: var(--primary-light);
}

.modal__action--secondary {
  background: rgba(255, 255, 255, 0.1);
  color: var(--text-secondary);
  border: 1px solid var(--border-primary);
}

.modal__action--secondary:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.2);
  color: var(--text-primary);
}

.modal__action--danger {
  background: var(--error-color);
  color: var(--text-primary);
}

.modal__action--danger:hover:not(:disabled) {
  background: #ff5252;
}

.modal__action--success {
  background: var(--success-color);
  color: var(--bg-primary);
}

.modal__action--success:hover:not(:disabled) {
  background: #00ff9f;
}

.modal__action--loading {
  pointer-events: none;
}

.modal__action-icon {
  width: 16px;
  height: 16px;
}

.modal__resize-handle {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 20px;
  height: 20px;
  cursor: nw-resize;
  background: linear-gradient(
    -45deg,
    transparent 0%,
    transparent 40%,
    var(--border-secondary) 40%,
    var(--border-secondary) 60%,
    transparent 60%
  );
}

/* 过渡动画 */
.modal-enter-active {
  transition: all 0.3s ease-out;
}

.modal-leave-active {
  transition: all 0.3s ease-in;
}

.modal-enter-from .modal-backdrop {
  opacity: 0;
}

.modal-enter-from .modal {
  opacity: 0;
  transform: scale(0.9) translateY(-20px);
}

.modal-leave-to .modal-backdrop {
  opacity: 0;
}

.modal-leave-to .modal {
  opacity: 0;
  transform: scale(0.9) translateY(-20px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .modal-backdrop {
    padding: var(--spacing-md);
  }
  
  .modal {
    width: 100% !important;
    height: 100% !important;
    max-width: none;
    max-height: none;
    border-radius: 0;
  }
  
  .modal__header {
    padding: var(--spacing-md);
  }
  
  .modal__content {
    padding: var(--spacing-md);
  }
  
  .modal__footer {
    padding: var(--spacing-md);
    flex-direction: column;
  }
  
  .modal__action {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .modal__title {
    font-size: var(--text-base);
  }
  
  .modal__footer {
    gap: var(--spacing-xs);
  }
}
</style>